package com.code.springbootwebsocket.service;

import com.code.springbootwebsocket.controller.v6.User;
import com.code.springbootwebsocket.model.InMessage;
import com.code.springbootwebsocket.model.OutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author: liyufei
 * @date: 2019-02-16 19:29
 */
@Service
public class WebSocketService {

    @Autowired
    private SimpMessagingTemplate template;

    public void sendTopicMessage(String dest, InMessage message) throws InterruptedException {
        for (int i = 0; i < 20; i++) {
            Thread.sleep(500L);
            template.convertAndSend(dest, OutMessage.builder().content(message.getContent()).build());
        }
    }

    public void sendChatMessage(InMessage message) {
        template.convertAndSend("/chat/single/" + message.getTo(),
                OutMessage.builder().content(message.getFrom() + " 发送: " +message.getContent()).build());
    }

    /**
     * 功能描述：获取系统信息，推送给客户端
     */
    public void sendServerInfo() {

        int processors = Runtime.getRuntime().availableProcessors();

        Long freeMem = Runtime.getRuntime().freeMemory();

        Long maxMem = Runtime.getRuntime().maxMemory();

        String message = String.format("服务器可用处理器:%s; 虚拟机空闲内容大小: %s; 最大内存大小: %s", processors,freeMem,maxMem );

        template.convertAndSend("/topic/server_info", OutMessage.builder().content(message).build());

    }

    public void sendOnlineUser(Map<String, User> onlineUser) {
        String msg = "";
        for(Map.Entry<String, User> entry : onlineUser.entrySet()){
            msg = msg.concat(entry.getValue().getUsername()+"||");
        }
        System.out.println(msg);
        template.convertAndSend("/topic/onlineuser",OutMessage.builder().content(msg).build());
    }

    public void sendTopicChat(InMessage message) {
        String msg = message.getFrom() +" 发送:"+message.getContent();
        template.convertAndSend("/topic/chat",OutMessage.builder().content(msg).build());
    }
}
